﻿using B.Rabbit.DataBase.Domain.Login;
using B.Rabbit.DataBase.ErrorCode;
using B.Rabbit.DataBase.Infrastructure.Infrastructure;
using B.Rabbit.DataBase.Read.Api.Applocation.Command.Login;
using B.Rabbit.DataBase.Read.Api.DTOs;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace B.Rabbit.DataBase.Read.Api.Applocation.Handler.Login
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, ApiResult<LoginDTOs>>
    {
        IBaseRepository<AccountModel> accountmodel;
        IBaseRepository<RoleModel> rolemodel;
        private readonly ILogger<LoginCommandHandler> _logger;
        public readonly IConfiguration configuration;

        public LoginCommandHandler(IBaseRepository<AccountModel> accountmodel, IBaseRepository<RoleModel> rolemodel, ILogger<LoginCommandHandler> logger, IConfiguration configuration)
        {
            this.accountmodel = accountmodel;
            this.rolemodel = rolemodel;
            _logger = logger;
            this.configuration = configuration;
        }

        /// <summary>
        /// 登录处理类
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<LoginDTOs>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<LoginDTOs> res = new ApiResult<LoginDTOs>();
            var account = accountmodel.GetList().Where(x => x.AccountName == request.AccountName || x.AccountPaw == request.AccountPaw).FirstOrDefault();
            if (account == null)
            {
                res.msg = "账号不存在，请注册";
                res.code = StatusCode.Fail;
                return await Task.FromResult(res);
            }
            if (account.AccountPaw != request.AccountPaw.GetMD5())
            {
                res.msg = "密码错误，请重新输入";
                res.code = StatusCode.Fail;
                return await Task.FromResult(res);
            }
            var role = await rolemodel.GetValue(account.RoleId);
            if (role == null)
            {
                res.msg = "角色不存在，请联系管理员";
                res.code = StatusCode.Fail;
                return await Task.FromResult(res);
            }
            var data = new LoginDTOs()
            {
                AccountName = account.AccountName,
                RealName = account.RealName,
                RoleName = role.RoleName,
                //Token= CreateTokenString(account.RealName,account.AccountName,role.RoleName)
            };
            res.msg = "恭喜您！登录成功";
            res.code = StatusCode.Ok;
            res.data = data;
            return await Task.FromResult(res);

        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString(string AccountName,string RealName,string RoleName)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(configuration["JWTConfiguration:privatekey"]);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: configuration["JWTConfiguration:issuer"],
                audience: configuration["JWTConfiguration:audience"],
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
